/*
 * htmlId.onclick( 'eventFunction(htmlId1, htmlId2)' )
 */

String.prototype.bind = function(eventFunctionStr) {
	var params = pickParams(eventFunctionStr)
  	var val = {}
	_$.each(params, function(idx, param){
    	val[param] = {}
		_$.each(getSubElemIds(param), function(i, id){
     	 	val[param][id] = {}
			var _this = _$('#' + id)
			
			if (_this.attr('contenteditable')) {
				_this.on('input', function(){
					val[param][id].val = _$(this).html()
					val[param][id].on = !!_$(this).html()
				})
			} else {
				_this.on('click', function() {
					_$(this).toggleClass('active')
					val[param][id].val = _$(this).attr('val')
					val[param][id].on = _$(this).hasClass('active')
				})
			}
		})
	})


    document.getElementById(this).addEventListener("click",function(){
        var paramString = '(' + JSON.stringify(val) + ')'

        var funcString = eventFunctionStr.replace(/\([^\)]*\)/g, paramString);
        try { 
			console.log(funcString)  
			console.log(JSON.parse(JSON.stringify(val)))
		} catch (error) { /* $.write(error) */ }

        try {
            cs.evalScript(funcString);
        } catch (error) {
            // alert(error)
        }
    })
}

'fitTarget'.bind('fitTarget(optionGroup, alignGroup)')

function pickParams(eventFunctionStr) {
	var start = eventFunctionStr.indexOf('(') + 1
	var end = eventFunctionStr.indexOf(')')
    var eventParams = eventFunctionStr.substring(start, end)
	functionParams = eventParams.split(',').map(function(item) {
		return item.trim()
	})
	return(functionParams)
}

function getSubElemIds(id) {
	var elemIds = []
	var liDoms = _$('#' + id).children('li').children('.item').each(function(index, elem) {
		var id = _$(elem).attr('id')
		elemIds.push(id)
	})
	return elemIds
}
